import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_view/photo_view.dart';

class CameraPage extends StatefulWidget{

  final CameraDescription camera;

  const CameraPage({Key key,@required this.camera}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return CameraPageState();
  }
  
}

class CameraPageState extends State<CameraPage>{

  CameraController _controller;
  Future<void> _initializeControllerFuture;
  
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _controller = CameraController(
      widget.camera,
      ResolutionPreset.ultraHigh
    );
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('相机测试')),
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context,snapshot){
          if(snapshot.connectionState == ConnectionState.done){
            return CameraPreview(_controller);
          }else{
            return Center(child: CircularProgressIndicator());
          }
        }
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.camera_alt),
        onPressed: () async{
          await _initializeControllerFuture;
          final path = join(
            (await getTemporaryDirectory()).path,
            '${DateTime.now()}.png'
          );
          await _controller.takePicture(path);
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ShowCameraImagePage(imagePath: path)
            )
          );
        }
      ),
    );
  }
}

class ShowCameraImagePage extends StatelessWidget{
  final String imagePath;

  const ShowCameraImagePage({Key key,@required this.imagePath}) :super(key: key);


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('拍照图片'),),
      body: Container(
        child: PhotoView(
          imageProvider: FileImage(File(imagePath)),
        )
      )
    );
  }}